
package com.iexbuy.ihg.ui.activity;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.ui.fragment.BaseFragment;
import com.iexbuy.ihg.utils.UnitUtils;
import com.umeng.analytics.MobclickAgent;

/**
 * @author chenguiban
 * 
 */
//public abstract class BaseActivity extends SwipeBackActivity {
public abstract class BaseActivity extends FragmentActivity {
	
	private static final int VIBRATE_DURATION = 20;
	private SwipeBackLayout mSwipeBackLayout;
	private boolean isSwipeBackEnable = true;
	
	protected BaseFragment mCurrentFragment;
	private RelativeLayout mTitleLayout;
	private TextView mTitle;
	private Button mLeftButton;
	private ImageView mDropButton;
	private Button mSlideMenuButton;
	private Button mSearchButton;
	private Button mHomeLeftButton;
	private Button mHomeRightButton;
	private Button mEditBtn;
	private boolean isFinishActivity = false;
	private boolean isHomeActivity = false;
	protected ProgressDialog mDialog;

	private long firstExitingTime = 0;
	private SharedPreferences sp;//存储


	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.base_layout);
		initHeaderView();
		init();
		CommUtil.addActivity(this);
		
		mCurrentFragment = getFragment();
		if (mCurrentFragment != null) {
			mCurrentFragment.startFragment(this, R.id.fragmentContainer);
		}
	}
	
	private void initHeaderView() {
		mTitleLayout = (RelativeLayout) findViewById(R.id.title);
		mTitle = (TextView) findViewById(R.id.txtTitle);
		mLeftButton = (Button) findViewById(R.id.btnBack);
		mSearchButton = (Button) findViewById(R.id.mSearchBtn);
		mSlideMenuButton = (Button) findViewById(R.id.mSlideMenuButton);
//		mEditBtn = (Button) findViewById(R.id.mEditBtn);
//		mRightButton = (Button) findViewById(R.id.headbar_rightbutton);
//		mHomeLeftButton = (Button) findViewById(R.id.home_leftbutton);
		mHomeRightButton = (Button) findViewById(R.id.btnRight);
		initLeftButton();
		initSlideMenuButton();
//		initEditButton(View.GONE, null);
	}

	public void setHomeLeftButton(OnClickListener onClickListener) {
		mHomeLeftButton.setOnClickListener(onClickListener);
		mHomeLeftButton.setVisibility(View.VISIBLE);
		mHomeLeftButton.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				mHomeLeftButton.performClick();
				return true;
			}
		});
	}

	public void setHomeLeftButtonBackgroundsResource(int resid) {
		mHomeLeftButton.setBackgroundResource(resid);
	}

	public void setRightButton(String text, OnClickListener onClickListener) {
		mHomeRightButton.setOnClickListener(onClickListener);
		mHomeRightButton.setText(text);
		LayoutParams lp = mHomeRightButton.getLayoutParams();
		lp.width = UnitUtils.dip2px(getApplicationContext(),40);
		mHomeRightButton.setLayoutParams(lp);
		mHomeRightButton.setVisibility(View.VISIBLE);
	}
	public void setRightButton(Drawable drawable, OnClickListener onClickListener) {
		mHomeRightButton.setOnClickListener(onClickListener);
		mHomeRightButton.setBackgroundDrawable(drawable);
		LayoutParams lp = mHomeRightButton.getLayoutParams();
		lp.width = UnitUtils.dip2px(getApplicationContext(),20);
		mHomeRightButton.setLayoutParams(lp);
		mHomeRightButton.setVisibility(View.VISIBLE);
	}

	public void setRightButton(String text, float testSize, OnClickListener onClickListener) {
		mHomeRightButton.setOnClickListener(onClickListener);
		mHomeRightButton.setTextSize(testSize);
		mHomeRightButton.setText(text);
		LayoutParams lp = mHomeRightButton.getLayoutParams();
		lp.width = UnitUtils.dip2px(getApplicationContext(), 80);
		mHomeRightButton.setLayoutParams(lp);
		mHomeRightButton.setVisibility(View.VISIBLE);
	}
	
	public void setRightButton(int resId, OnClickListener onClickListener) {
		mHomeRightButton.setOnClickListener(onClickListener);
		mHomeRightButton.setBackgroundResource(resId);
		LayoutParams lp = mHomeRightButton.getLayoutParams();
		lp.width = UnitUtils.dip2px(getApplicationContext(), 30);
		lp.height = UnitUtils.dip2px(getApplicationContext(), 30);
		mHomeRightButton.setLayoutParams(lp);
		mHomeRightButton.setVisibility(View.VISIBLE);
	}
	
	public void setRightButton(int resId, OnClickListener onClickListener, int width) {
		mHomeRightButton.setOnClickListener(onClickListener);
		mHomeRightButton.setBackgroundResource(resId);
		LayoutParams lp = mHomeRightButton.getLayoutParams();
		lp.width = UnitUtils.dip2px(getApplicationContext(), width);
		lp.height = UnitUtils.dip2px(getApplicationContext(), 30);
		mHomeRightButton.setLayoutParams(lp);
		mHomeRightButton.setVisibility(View.VISIBLE);
	}

	private void initLeftButton() {
		mLeftButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				handleBack();
			}
		});
		mLeftButton.setOnTouchListener(new OnTouchListener() {
            @Override 
            public boolean onTouch(View arg0, MotionEvent arg1) { 
            	mLeftButton.performClick();
            	return true;
            }
        });
	}
	
	private void setDropButton(OnClickListener mOnClickListener) {
		mDropButton.setVisibility(View.VISIBLE);
		mDropButton.setOnClickListener(mOnClickListener);
		mTitle.setOnClickListener(mOnClickListener);
	}
	
	private void initSlideMenuButton() {
		mSlideMenuButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				if (MainTabActivity.getInstance() != null) {
//					MainTabActivity.getInstance().toggleSlidingMenu();
//				}
			}
		});
		mSlideMenuButton.setVisibility(View.GONE);
	}
	
	public void enableSlideMenuButtonTouch(boolean isEnable) {
//		if (MainTabActivity.getInstance() != null) {
//			MainTabActivity.getInstance().enableSlidingMenuTouch(isEnable);;
//		}
	}
	
//	public void initSlideMenuList(List<ApplicationTag> tagNameArray, int[] tagIconArray, OnItemClickListener listener) {
//		if (MainTabActivity.getInstance() != null) {
//			MainTabActivity.getInstance().initSlideMenuList(tagNameArray, tagIconArray, listener) ;
//		}
//	}
	
	public void initEditButton(int visible, OnClickListener mOnClickListener) {
		mEditBtn.setOnClickListener(mOnClickListener);
		mEditBtn.setVisibility(visible);
	}

	/*
	 * public void setHeaderHomeIconVisibility(int Visibility) {
	 * mHomeIcon.setVisibility(Visibility); }
	 */

	public void setLeftButton(String text, OnClickListener onClickListener) {
		mLeftButton.setText(text);
		if (onClickListener != null) mLeftButton.setOnClickListener(onClickListener);
		mLeftButton.setVisibility(View.VISIBLE);
	}

	public void setLeftButtonVisibility(int visible) {
		mLeftButton.setVisibility(visible);
	}

	public void setSearchButtonVisibility(int visible, OnClickListener mOnClickListener) {
		mSearchButton.setOnClickListener(mOnClickListener);
		mSearchButton.setVisibility(visible);
	}
	
	protected String getTitle(Intent intent) {
		String title = null;
		if (intent != null)
			title = intent.getStringExtra(ExtraKeyConstant.KEY_TITLE);
		return title;
	}
	
	public void initSlideRightBack() {
//		mSwipeBackLayout = getSwipeBackLayout();
//		mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
//		mSwipeBackLayout.addSwipeListener(new SwipeBackLayout.SwipeListener() {
//			@Override
//			public void onScrollStateChange(int state, float scrollPercent) {
//			}
//
//			@Override
//			public void onEdgeTouch(int edgeFlag) {
//				//vibrate(VIBRATE_DURATION);
//			}
//
//			@Override
//			public void onScrollOverThreshold() {
//				// vibrate(VIBRATE_DURATION);
//			}
//		});
	}

	public void setSlideRightBackEnable(boolean enable) {
		if (mSwipeBackLayout != null) {
			mSwipeBackLayout.setEnabled(enable);
		} else {
			isSwipeBackEnable = enable;
		}
	}

	
	private void vibrate(long duration) {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {0, duration};
        vibrator.vibrate(pattern, -1);
    }

	@Override
	protected void onResume() {
		super.onResume();
//		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
//		MobclickAgent.onPause(this);
	}

	public void setTitle(CharSequence title) {
		mTitle.setOnClickListener(null);
		if (!TextUtils.isEmpty(title)) {
			mTitle.setText(title);
			mTitleLayout.setVisibility(View.VISIBLE);
		} else {
			mTitleLayout.setVisibility(View.GONE);
		}
	}

	public void setTitleLayoutVisibility(boolean isvisiblity) {
		if (isvisiblity) {
			mTitleLayout.setVisibility(View.VISIBLE);
		} else {
			mTitleLayout.setVisibility(View.GONE);
		}
	}

	/**
	 * 
	 * head bar left return button
	 */
	protected int onBack() {
		int count = 1;

//		if (MainTabActivity.getInstance() != null && MainTabActivity.getInstance().isMenuOpen()) { // 
//			MainTabActivity.getInstance().closeSlidingMenu();
//			count = 0;
//		} else 
			
		if (mCurrentFragment != null) {
			if (mCurrentFragment.onKeyDown(KeyEvent.KEYCODE_BACK, null))
				count = 0;
			else
				count = mCurrentFragment.finish(this);
		}
		
		Log.i(getClass().getSimpleName(), "onBack():"+count);
		
		return count;
	}
	
	public void initHandleMiddleNavDbClick() {
//		MainTabActivity.getInstance().addMiddleNavBtnClickLisener(new MiddleNavBtnClickLisener() {
//			@Override
//			public void onMiddleNavBtnDbClick() {
//				onBack();
//			}
//		});
	}

	public abstract void init();

	/**
	 * call in onCreate()
	 * 
	 * @return
	 */
	protected abstract BaseFragment getFragment();

	public void setCurrentFragment(BaseFragment mCurrentFragment) {
		this.mCurrentFragment = mCurrentFragment;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			handleBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void handleBack() {
		Log.i(getClass().getSimpleName(), "handleBack()? onback=1, isFinishActivity="+isFinishActivity+",isHomeActivity="+isHomeActivity);
		sp=getSharedPreferences("config", Context.MODE_PRIVATE);
		boolean finish=sp.getBoolean("finish", true);//判断写的存储
		if (onBack() == 1) {
			if (isFinishActivity) {
				finish();
			} else {
				eixtApp();
			}
		}
	}

	private void eixtApp() {
		Log.i(getClass().getSimpleName(), "eixtApp(), exitingtime="+(System.currentTimeMillis() - firstExitingTime));
		if ((System.currentTimeMillis() - firstExitingTime) > 2000) {
			Toast.makeText(getApplicationContext(), "再次点击返回键退出应用", Toast.LENGTH_SHORT).show();
			firstExitingTime = System.currentTimeMillis();
		} else {
			Log.i(getClass().getSimpleName(), "eixtApp()=1, activity list="+ App.sActivityList.size());
//			App.sPreferences.setLoginIn(false);
			MobclickAgent.onKillProcess(BaseActivity.this);
			CommUtil.exit(BaseActivity.this);
		}
	}

	public boolean isFinishActivity() {
		return isFinishActivity;
	}

	public void setFinishActivity(boolean isFinishActivity) {
		this.isFinishActivity = isFinishActivity;
	}

	/**
	 * 
	 * @param bundle
	 * @return
	 */
	public boolean checkLoginIn(Bundle bundle) {
//		if (UserInfoControler.getInstance().checkUserLoginIn());
//			return true;
//		Intent intent = new Intent(this, LoginActivity.class);
//		if (bundle != null)
//			intent.putExtras(bundle);
//		if (mCurrentFragment != null)
//			mCurrentFragment.startActivityForResult(intent, 1);
//		else
//			startActivityForResult(intent, 1);

		return true;
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);

	}

	/**
	 * @param isHomeActivity
	 *            the isHomeActivity to set
	 */
	public void setHomeActivity(boolean isHomeActivity) {
		this.isHomeActivity = isHomeActivity;
	}

	public boolean isHomeActiviry(){
		return this.isHomeActivity;
	}
	
	
	/**
	 * ??�示titlelayaout
	 */
	public void showTitle() {
		mTitleLayout.setVisibility(View.VISIBLE);
	}
	
	
	public void setTitle(CharSequence title, OnClickListener mOnClickListener) {
		this.setTitle(title);
//		setDropButton(mOnClickListener);
	}
	
	public void setSlideMenuButtonVisible(int visible){
		mSlideMenuButton.setVisibility(visible);
	}
	
	/**
	 */
	public void hideRightMenu () {
		if (mHomeRightButton != null) {
			mHomeRightButton.setVisibility(View.GONE);
		}
	}
	
	public void showDialog(String text){
		mDialog = ProgressDialog.show(this, null, text);  
		mDialog.setCanceledOnTouchOutside(false);
		mDialog.setIndeterminate(true);
		mDialog.setCancelable(true);
	}
	
	public void closeDialog(){
		try {
			if (mDialog != null)
				mDialog.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {

		}
		return true;
	}

	public void startActivityForResult(int requestCode,int resultCode,Intent intent) {
		switch(requestCode){
		case RESULT_OK:
			Bundle bundle=intent.getExtras();
		}
	}


}
